package demo.config;

import demo.handler.HttpErrorHandler;
import demo.intercepter.LoginIntercepter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.util.UrlPathHelper;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = {
		"demo"
})
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private LoginIntercepter loginIntercepter;

	/* http://stackoverflow.com/questions/3526523/spring-mvc-pathvariable-getting-truncated */
	@Override
	public void configurePathMatch(PathMatchConfigurer configurer) {
		configurer.setUseTrailingSlashMatch(true);
		configurer.setUseSuffixPatternMatch(false);
		configurer.setUseRegisteredSuffixPatternMatch(false);

		AntPathMatcher antPathMatcher = new AntPathMatcher();
		antPathMatcher.setTrimTokens(false);
		antPathMatcher.setCaseSensitive(false);
		configurer.setPathMatcher(antPathMatcher);

		UrlPathHelper urlPathHelper = new UrlPathHelper();
		urlPathHelper.setDefaultEncoding("UTF-8");
		urlPathHelper.setAlwaysUseFullPath(true);
		urlPathHelper.setUrlDecode(true);
		configurer.setUrlPathHelper(urlPathHelper);
	}

	@Bean
	public HttpErrorHandler httpErrorHandler() {
		return new HttpErrorHandler();
	}

	@Bean
	public  CommonsMultipartResolver multipartResolver() {
		return new CommonsMultipartResolver();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
	    registry.addInterceptor(loginIntercepter)
                .addPathPatterns("/auth");
    }
}
